<template>
	<article>
        <i class="el-icon-close close-top" @click="cancel"></i>
		<el-form :inline="true" :model="form" class="demo-form-inline">
            <el-form-item label="选择老师">
                <el-select v-model="form.teacher" placeholder="请选择老师" @change="selectChange">
                    <el-option :label="v.zwm" :value="v.id" v-for="v in teacherList"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="选择年月">
                <el-date-picker v-model="form.time" type="date" placeholder="选择日期" @change="changeDate"></el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="text" @click="pre"><上周></el-button>
                <el-button type="text" @click="next"><下周></el-button>
            </el-form-item>
        </el-form>



        <!-- 数据表格展示区域 -->
        <el-table
            :data="dataList"
            border
            align="center"
            class="admin-table">

            <div slot='empty'>
                <img src="../../../assets/img/empty.png" style="width:40px;vertical-align: middle;">
                <span style="vertical-align: middle;">暂时还没有内容哦!</span>
            </div>
            <el-table-column
                :prop="v.prop"
                :label="v.label"
                :column-key="v.number"
                v-for="(v,index) in portTitleList"
                align="center"
                show-overflow-tooltip
                v-if="v.hide != 0"
                :render-header="headerHtml"
                :align="v.align || 'center'"
                :fixed="v.fixed"
                :class-name="v.columnStyle"
                :width="v.width || 180"
                :min-width="v.minWidth"
                :header-align="v.headerAlign || 'center'"
                >
                <template scope="scope">
                    <div slot="reference" >
                        <div v-if="scope.column.property == 'sjd'">{{ scope.row[scope.column.property] }}</div>
                        <div v-else v-html="isTeacher(scope)"></div>
                        <!-- <span v-if="scope.column.property == 'lessons' || scope.column.property == 'sjd'">{{ scope.row[scope.column.property] }}</span>
                        <span v-else-if="isTeacher(scope)">

                            <div v-if="isTeacher(scope).bol" class="teacher" @click="changeType(isTeacher(scope).title.split('-')[1])">
                                <img src="../../../assets/img/teacher.png" style="width:20px;vertical-align:middle">
                                <span v-text="isTeacher(scope).title.split('-')[0]" style="vertical-align:middle"></span>
                            </div>
                            <div v-else>


                                <div v-if="isTeacher(scope).title === '双休'" class="cell-box">
                                    <img src="../../../assets/img/rest.png" style="width:24px;">
                                </div>
                                <span v-else v-text="isTeacher(scope).title"></span>
                            </div>
                        </span>
                        <div v-else @click="choose(scope)" class="cell-box">
                            <img src="../../../assets/img/none.png" style="width:24px;">
                        </div> -->

                    </div>
                 </template>
            </el-table-column>


        </el-table>


        <!-- 老师编辑 -->
        <el-dialog :visible.sync="changeTeacher" :modal-append-to-body="false" size="tiny" class="DelorUpdate">
            <h2>更换 OR  删除</h2>
            <div class="btn">
                <el-button type="info" @click="updateTeacher()">更换老师</el-button>
                <el-button type="danger" @click="delTeacher()">删除老师</el-button>
            </div>
        </el-dialog>


        <!-- 选择老师 -->
        <el-dialog title="选择老师" :visible.sync="tableShow" :modal-append-to-body="false" size="tiny">

            <el-select v-model="chooseTeacherID" filterable placeholder="请选择老师" class="show change-teacher">
                <el-option
                  v-for="item in teacherList"
                  :label="item.zwm"
                  :value="item.id">
                </el-option>
            </el-select>

            <el-button type="info" class="affirm" @click="affirm">提交</el-button>
        </el-dialog>


        <!-- 节假日管理 -->

	</article>
</template>

<script type="text/javascript">
	export default {
        props: ['params'],
        data () {
            return {
                isLoading: false,
                tableShow: false,

                dialogType: 'add',

                form: {
                    teacher: '', //教室ID
                    time: ''  //当前时间
                },
                currentTime: '', //当前星期几

                timeVal: '', //显示 xx-xx-xx
                schedulingTime: '',  //获取排课列表需要的字段时间



                dataList: [
                    { sjd: '早上', type: 'am'},
                    { sjd: '中午', type: 'pm'},
                    { sjd: '晚上', type: 'night'}
                ], //排课list

                allList: [], //排课所有信息
                allTimeList: [],
                // allIDList: [],
                // allNameList: [],


                changeTeacher: false, //删除老师还是设置老师弹层

                nowTeacherID: '',//当前老师ID

                chooseTeacherID: '', //选择排课老师
                chooseTimeID: '', //选择排课时间段ID
                // chooseTime: '', //选择排课时间
                classroomList: [], //获取教室列表
                teacherList: [], //获取老师列表
                lessons: ['第一节','第二节','第三节','第四节','第五节','第六节','第七节','第八节','第九节','第十节'],
                timeFrame: [
                    {key: '8-12', value: '早上'},
                    {key: '12', value: '中午'},
                    {key: 'night', value: '晚上'}
                ], //时间段

                holidaysList: [], //假期列表
                HolidaysTime:[],
                HolidaysName: [],

                portTitleList: [
                    {
                        prop:'sjd',
                        label:'时段',
                        hide:1,
                        align:'center',
                        fixed:false,
                        width:'',
                        minWidth:'',
                        headerAlign:'center',
                        formatter: function(row,column) {}
                    },
                    {
                        prop:'one',
                        label:'周一',
                        number:'2',
                        hide:1,
                        align:'center',
                        fixed:false,
                        width:'',
                        minWidth:'',
                        headerAlign:'center',
                        formatter: function(row,column) {}
                    },
                    {
                        prop:'two',
                        label:'周二',
                        number:'3',
                        hide:1,
                        align:'center',
                        fixed:false,
                        width:'',
                        minWidth:'',
                        headerAlign:'center',
                        formatter: function(row,column) {}
                    },
                    {
                        prop:'three',
                        label:'周三',
                        number:'4',
                        hide:1,
                        align:'center',
                        fixed:false,
                        width:'',
                        minWidth:'',
                        headerAlign:'center',
                        formatter: function(row,column) {}
                    },
                    {
                        prop:'four',
                        label:'周四',
                        number:'5',
                        hide:1,
                        align:'center',
                        fixed:false,
                        width:'',
                        minWidth:'',
                        headerAlign:'center',
                        formatter: function(row,column) {}
                    },
                    {
                        prop:'five',
                        label:'周五',
                        number:'6',
                        hide:1,
                        align:'center',
                        fixed:false,
                        width:'',
                        minWidth:'',
                        headerAlign:'center',
                        formatter: function(row,column) {}
                    },
                    {
                        prop:'six',
                        label:'周六',
                        number:'7',
                        hide:1,
                        align:'center',
                        fixed:false,
                        width:'',
                        minWidth:'',
                        headerAlign:'center',
                        formatter: function(row,column) {}
                    },
                    {
                        prop:'seven',
                        label:'周日',
                        number:'8',
                        hide:1,
                        align:'center',
                        fixed:false,
                        width:'',
                        minWidth:'',
                        headerAlign:'center',
                        formatter: function(row,column) {}
                    },

                ],
            }
        },
        created () {
            // this.$store.dispatch('changeTitle',"添加班级 ")
            // console.log(this.params)

            this.$store.dispatch('changeTitle','老师课表');//修改title
            this.$store.dispatch('changeRouterIndex', '/admin/teachercourse');//修改路由


            this.form.time = new Date();
            // this.timeVal = this.$.getMonthDay(new Date().getTime());
            this.timeVal = this.$.getLocalTime(new Date().getTime());

            this.currentTime = this.form.time.getDay();

            this.schedulingTime = this.$.getLocalTime(new Date().getTime());

            this.getClassroomList();
            this.getHolidays(); //获取假期
            this.getTeacherList(); //获取老师

            // console.log(this.timeVal)

            // this.getSchedulingList();
        },
        methods: {
            changeDate (val) {
                this.timeVal = val;
                this.currentTime = new Date(val).getDay();
                this.schedulingTime = val;
                // console.log(this.currentTime)
                console.log(this.timeVal)
                this.getSchedulingList();
            },
            headerHtml (h, { column, $index }) {
                if ($index == 1) {
                    return "周一("+ this.$.changeDateFormat(this.$.updateDate(this.$.getLocalTime(Date.parse(new Date(this.form.time))),$index - this.currentTime)) + ')';
                }else if($index == 2){
                    return "周二("+ this.$.changeDateFormat(this.$.updateDate(this.$.getLocalTime(Date.parse(new Date(this.form.time))),$index - this.currentTime)) + ')';
                }else if($index == 3){
                    return "周三("+ this.$.changeDateFormat(this.$.updateDate(this.$.getLocalTime(Date.parse(new Date(this.form.time))),$index - this.currentTime)) + ')';
                }else if($index == 4){
                    return "周四("+ this.$.changeDateFormat(this.$.updateDate(this.$.getLocalTime(Date.parse(new Date(this.form.time))),$index - this.currentTime)) + ')';
                }else if($index == 5){
                    return "周五("+ this.$.changeDateFormat(this.$.updateDate(this.$.getLocalTime(Date.parse(new Date(this.form.time))),$index - this.currentTime)) + ')';
                }else if($index == 6){
                    return "周六("+ this.$.changeDateFormat(this.$.updateDate(this.$.getLocalTime(Date.parse(new Date(this.form.time))),$index - this.currentTime)) + ')';
                }else if($index == 7){
                    return "周日("+ this.$.changeDateFormat(this.$.updateDate(this.$.getLocalTime(Date.parse(new Date(this.form.time))),$index - this.currentTime)) + ')';
                }else{
                    return column.label;
                }
            },

            // 判断该节课是否有老师
            isTeacher (scope) {
                var timeID = scope.row.sjdid;
                var time = this.$.updateDate(this.$.getLocalTime(Date.parse(new Date(this.form.time))),scope.column.columnKey - (this.currentTime + 1));
                // var index = scope.$index;

                var date = time.split("-")
                date.splice(0,1)
                date = date.join("-")

                // console.log(scope)
                // console.log(this.allTimeList)
                var type = scope.row.type
                var index = this.allTimeList.indexOf(date)
                if (index >= 0) {

                    var html = '';

                    var html = '';
                    var am = false,pm = false, night = false;

                    // console.log(scope)
                    this.allList[index].items.forEach( v => {
                        var arr = v.sjd.split('-')
                        var num = arr[1].trim().substring(0,2);
                        // numArr.push(num);
                        if (num <= 12) am = true;
                        if (num > 12 && num <= 18) pm = true;
                        if (num > 18) night = true;

                        if ( type == 'am' && num <= 12) {
                            html +=  `
                                <p>
                                    <span>${v.className}</span>
                                    <span>${v.sjd}</span>
                                </p>
                            `
                        }

                        if ( type == 'pm' && num <= 18 && num > 12) {
                            html +=  `
                                <p>
                                    <span>${v.className}</span>
                                    <span>${v.sjd}</span>
                                </p>
                            `
                        }

                        if ( type == 'night' && num > 18) {
                            html +=  `
                                <p>
                                    <span>${v.className}</span>
                                    <span>${v.sjd}</span>
                                </p>
                            `
                        }
                    })
                    if (type == 'am') {
                        if (!am) return '-';
                        return(html)
                    }

                    if (type == 'pm') {
                        if (!pm) return '-';
                        return(html)
                    }

                    if (type == 'night') {
                        if (!night) return '-';
                        return(html)
                    }
                }else{
                    return '-'
                }

            },

            //点击进行排课
            choose (scope) {
                this.getTeacherList();
                this.dialogType = 'add';

                this.schedulingTime = this.$.updateDate(this.$.getLocalTime(Date.parse(new Date(this.form.time))),scope.column.columnKey - (this.currentTime + 1));
                this.chooseTimeID = scope.row.sjdid;
                this.tableShow = true;
            },

            changeType(id) {
                // alert(id)
                this.changeTeacher = true
                this.nowTeacherID = id;
            },

            //点击删除老师
            delTeacher () {
                this.changeTeacher = false;

                this.$confirm('此操作将删除该课表的老师, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {

                    this.axios.get(this.$store.state.api + 'pk/del', {
                        params: {
                            id: this.nowTeacherID
                        }
                    })
                    .then( res => {
                        console.log( res)

                        if (res.data.code == 1) {
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                            this.getSchedulingList ();
                        }
                    }).catch( res => {
                        console.log( res )
                    })


                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });



            },

            updateTeacher () {//更换老师
                this.getTeacherList();
                this.dialogType = 'update';
                this.changeTeacher = false;
                this.tableShow = true;
            },
            updateCourse () { //更换课程
                // console.log(this.nowTeacherID,this.chooseTeacherID)
                this.$store.state.loading = true;
                this.axios.get(this.$store.state.api + 'pk/update', {
                    params: {
                        id: this.nowTeacherID,
                        lsid: this.chooseTeacherID
                    }
                })
                .then( res => {
                    console.log( res)
                    if (res.data.code == 1) {
                        this.tableShow = false;
                        this.$store.state.loading = false;
                        this.getSchedulingList ();
                    }

                }).catch( res => {
                    console.log( res );
                    this.$store.dispatch('showAlert',res.data.msg)
                    this.$store.state.loading = false;
                })
            },

            affirm () {  //确认排课
                if (!this.chooseTeacherID) {
                    this.$message.error('请选择老师');
                    return
                }

                if (this.dialogType == 'add') {
                   this.addCourse();
                }else if(this.dialogType == 'update'){
                    this.updateCourse()
               }

            },

            getHolidays () { //获取节假日
                this.axios.get(this.$store.state.api + 'jjr/list_rq', {
                    params: {
                        rq: this.timeVal
                    }
                }).then( res => {
                    console.log(res)
                    this.holidaysList = res.data.data.list;

                    this.holidaysList.forEach( v => {
                        var arr = v.rq.split('-');
                        var time = arr[1] + '-' + arr[2]

                        this.HolidaysTime.push(time)
                        this.HolidaysName.push(v.sm)
                    })
                    console.log(this.HolidaysTime,this.HolidaysName)

                }).catch( res => {
                    console.log(res)
                })

            },

            getSchedulingList () { //获取排课列表
                this.$store.state.loading = true;
                // this.axios.get(this.$store.state.api + '/pk/list', {
                //     params: {
                //         jsid: this.form.classroom,
                //         bjid: this.params.row.id,
                //         sj: this.schedulingTime
                //     }
                // }).then( res => {
                //     console.log(res)
                //     this.allList = res.data.data.list;
                //     this.$store.state.loading = false;
                // }).catch( res => {
                //     console.log(res)
                //     // this.$store.dispatch('showAlert',res.data.msg)
                //     this.$store.state.loading = false;
                // })
                this.axios.get(this.$store.state.api + 'pk/ls', {
                    params: {
                        id: this.form.teacher,
                        rq: this.timeVal
                    }
                }).then( res => {
                    console.log(res)
                    console.log({
                        id: this.form.teacher,
                        rq: this.timeVal
                    });
                    // this.dataList = res.data.list;
                    this.allList = res.data.data.list;

                    this.allList.forEach( v => {
                        var arr = v.time.split("-");
                        var time = arr[1] + '-' + arr[2];
                        this.allTimeList.push(time);
                    })

                    this.$store.state.loading = false;
                }).catch( res => {
                    console.log(res)
                    // this.$store.dispatch('showAlert',res.data.msg)
                    this.$store.state.loading = false;
                })
            },
            getClassroomList () { //获取教室列表
                this.axios.get(this.$store.state.api + '/xxjs/list', {

                }).then( res => {
                    console.log(res)
                    this.classroomList = res.data.data.list;
                }).catch( res => {
                    console.log(res)
                })
            },
            getTeacherList () { //获取老师列表
                this.axios.get(this.$store.state.api + 'pk/teachlist')
                // this.axios.get(this.$store.state.api + 'emp/lslist')
                .then( res => {
                    console.log(res)
                    // this.teacherList = res.data.data.lslist;
                    res.data.data.lslist.forEach( (v, i) => {
                        if (v.emptype === "ls") {
                            this.teacherList.push(v);
                        }
                    })
                }).catch( res =>{
                    console.log(res)
                })
            },
            selectChange (id) { //选择教室
                // this.getSchedulingList()
                // this.getTimeList (id);
                this.getSchedulingList()
            },
            /*getTimeList (id) { //获取时间段
                return new Promise( (resolve, reject) => {
                    this.axios.get(this.$store.state.api + 'jssjd/list', {
                        params: {
                            jsid: id
                        }
                    }).then( res => {
                        console.log(res);
                        this.timeFrame = res.data.data.list;
                        resolve ()
                    }).catch( res => {
                        console.log(res);
                    })
                })

            },*/
            addCourse () { //添加排课信息
                this.axios.get(this.$store.state.api + 'pk/add', {
                    params: {
                        bjid: this.params.row.id ,
                        jsid: this.form.classroom,
                        lsid: this.chooseTeacherID,
                        sjdid: this.chooseTimeID,
                        sj: this.schedulingTime
                    }

                }).then( res => {
                    console.log(res);
                    if (res.data.code == 1) {
                        this.tableShow = false;
                        this.getSchedulingList ();
                    }
                }).catch( res => {
                    console.log(res);
                })
            },


            pre () { //上一周
                this.strdate(this.timeVal, 'pre')
                // console.log(this.timeVal)
            },

            next () { //下一周
                this.strdate(this.timeVal, 'next')
                // console.log(this.timeVal)
            },
            cancel () {
               this.$emit('close',{type:'pk',calcel:true})
            },
            tableCellControl (scope) {//表格单元格控制CSS样式
                /*if (scope.row.id == 112 && scope.column.property == "iname") {
                    return {
                        color:"red",
                    }
                }else{
                    return {
                        color:"green",
                    }
                }*/
            },
            datestr (yy, mm, dd, prenext) {
                var s, d, t, t2;
                t = Date.UTC(yy, mm, dd);
                t2 = 7 * 1000 * 3600 * 24; //加减7天的时间
                if (prenext == 'pre') {
                    t-= t2;
                } else {
                    t+= t2;
                }
                d = new Date(t);
                s = d.getUTCFullYear() + "-";
                s += ("00"+(d.getUTCMonth()+1)).slice(-2) + "-";
                s += ("00"+d.getUTCDate()).slice(-2);
                this.form.time = s;
            },

            strdate(str, prenext){
                var dd, mm, yy, arr;
                var reg = /^(\d{4})-(\d{1,2})-(\d{1,2})$/;
                if (arr = str.match(reg)) {
                    yy = Number(arr[1]);
                    mm = Number(arr[2])-1;
                    dd = Number(arr[3]);
                } else {
                    var d = new Date();
                    yy = d.getUTCFullYear();
                    mm = ("00"+(d.getUTCMonth())).slice(-2);
                    dd = ("00"+d.getUTCDate()).slice(-2);
                }
                if (prenext == null || (prenext != 'pre' && prenext != 'next')) {
                    var prenext = 'pre';
                }
                this.datestr(yy, mm, dd, prenext);
            }
        },
        watch: {
            // dataList () {
            //     this.dataList.forEach( (v, i) => {
            //         v.time = this.timeFrame[i].sjd
            //     })
            // },
            // timeFrame () {
            //     this.timeFrame.forEach( (v, i) => {

            //     })
            //     this.$set(this.dataList)
            // }


        }
    }
</script>

<style lang="less" scope>
    .affirm {
        width: 120px;
        display: block;
        margin:20px auto;
        margin-bottom:0;
    }

    .change-teacher {
        /* width: 60%;
        margin:0 auto; */
        min-width:200px;
    }

    .teacher {
        cursor: pointer;

        &:hover span{
            text-decoration: underline;
            color: #4db3ff;
        }

    }
    .cell-box {
        display: flex;
        align-items:center;
        justify-content: center;
        cursor: pointer;
    }

    .DelorUpdate {
        h2 {
            text-align: center;
            font:20px;
        }

        .btn {
            margin-top:20px;
            text-align: center;
        }
    }
</style>
